package com.glsc.ngateway.opmanage.service.xinyi;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.glsc.ngateway.common.api.common.enums.Constant;
import com.glsc.ngateway.common.api.common.utils.PageUtil;
import com.glsc.ngateway.common.api.oaflow.dto.XinYiParamDto;
import com.glsc.ngateway.common.base.domain.mysql.gateway.platform.User;
import com.glsc.ngateway.common.base.domain.mysql.opmanagemain.xinyi.XinYiDefineLog;
import com.glsc.ngateway.common.base.domain.mysql.opmanagemain.xinyi.XinYiDefineTemplate;
import com.glsc.ngateway.common.base.domain.mysql.opmanagemain.xinyi.XinYiDefineTemplateItem;
import com.glsc.ngateway.common.base.repo.mysql.opmanagemain.xinyi.XinYiDefineTemplateRepository;
import com.glsc.ngateway.opmanage.service.SystemConfigService;
import com.glsc.ngateway.opmanage.service.feign.GatewayFeignService;
import com.glsc.ngateway.opmanage.utils.DateUtils;
import com.glsc.ngateway.opmanage.utils.SpecificationUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

@Service
@Slf4j
public class XinYiDefineTemplateService {
    private static final Integer GATEWAY_RET_CODE_SUCCESS = 0;
    @Resource
    private SystemConfigService systemConfigService;

    @Resource
    private XinYiDefineTemplateRepository xinYiDefineTemplateRepository;

    @Resource
    private XinYiDefineTemplateItemService xinYiDefineTemplateItemService;

    @Resource
    private GatewayFeignService gatewayFeignService;

    @Resource
    private XinYiDefineLogService xinYiDefineLogService;

    /**
     * 分页查询
     *
     * @param pageNo
     * @param pageSize
     * @param param
     * @return
     */
    public Page<XinYiDefineTemplate> page(int pageNo, int pageSize, Map<String, Object> param) {
        Sort.Direction direction = Sort.Direction.DESC;
        String sort = "createTime";

        pageNo = PageUtil.initPageNo(pageNo);
        pageSize = PageUtil.initPageSize(pageSize);

        Pageable pageable = PageRequest.of(pageNo - 1, pageSize, direction, sort);
        Page<XinYiDefineTemplate> page = xinYiDefineTemplateRepository.findAll(SpecificationUtil.buildSpecification(param, XinYiDefineTemplate.class), pageable);

        return page;
    }

    /**
     * 根据id查找
     *
     * @param id
     * @return
     */
    public XinYiDefineTemplate findById(Integer id) {
        Optional<XinYiDefineTemplate> optional = xinYiDefineTemplateRepository.findById(id);
        if (optional.isPresent()) {
            return optional.get();
        }
        return null;
    }

    /**
     * 保存
     *
     * @param obj
     * @return
     */
    public XinYiDefineTemplate save(XinYiDefineTemplate obj) {
        return xinYiDefineTemplateRepository.save(obj);
    }

    /**
     * 根据id删除
     *
     * @param id
     */
    public void deleteById(Integer id) {
        xinYiDefineTemplateRepository.deleteById(id);
    }

    /**
     * 发送新意指令
     *
     * @param id
     * @param user
     */
    public void send(Integer id, User user) {
        XinYiDefineTemplate template = findById(id);
        if (Objects.isNull(template)) {
            return;
        }

        List<XinYiDefineTemplateItem> items = xinYiDefineTemplateItemService.findByTemplateId(id);
        if (CollectionUtil.isEmpty(items)) {
            return;
        }
        String date = DateUtils.reFormatDate(DateUtils.getNowDateString(), DateUtils.formatDate_, DateUtils.formatDate);


        for (XinYiDefineTemplateItem item : items) {
            try {
                String paramJson = systemConfigService.findConfigValueByCode(Constant.CONFIG_KEY_SYNC_OA_FORM_DATA_XIN_YI_FIELD);
                XinYiParamDto paramDto = JSONObject.parseObject(paramJson, XinYiParamDto.class);
                paramDto.setOutInstId("glsc-" + System.currentTimeMillis());

                paramDto.buildRecInfo(item.getRecBankAccName(), item.getRecBankAcc(), item.getRecOpenAccountBank(), "9999")
                        .buildPayInfo(item.getPayBankAccName(), item.getPayBankAcc(), item.getPayOpenAccountBank(), "9999")
                        .buildDateInfo(date, date, date)
                        .setOccurAmt(item.getOccurAmt()).setNote(item.getMemo())
                        .setPayBigBankAcc(item.getPayBigBankAcc())
                        .setRecBigBankAcc(item.getRecBigBankAcc());

                if (StringUtils.isEmpty(paramDto.getNote())) {
                    paramDto.setNote("默认划款摘要");
                }

                String ret = gatewayFeignService.callXy(JSON.toJSONString(paramDto));
//            String ret = "";
//            JSONObject retObject = new JSONObject();
                JSONObject retObject = JSONObject.parseObject(ret);

                XinYiDefineLog yiDefineLog = XinYiDefineLog.builder().name(template.getName()).templateId(template.getId()).occurAmt(item.getOccurAmt()).deleted("N")
                        .recBankAcc(item.getRecBankAcc()).recBankAccName(item.getRecBankAccName()).recOpenAccountBank(item.getRecOpenAccountBank()).recBigBankAcc(item.getRecBigBankAcc())
                        .payBankAcc(item.getPayBankAcc()).payBankAccName(item.getPayBankAccName()).payOpenAccountBank(item.getPayOpenAccountBank()).payBigBankAcc(item.getPayBigBankAcc())
                        .type(template.getType()).build();
                yiDefineLog.setStatus("Y");

                if (StrUtil.isEmpty(ret) || null == retObject || null == retObject.get("code") || !GATEWAY_RET_CODE_SUCCESS.equals(retObject.get("code"))
                        || Objects.isNull(retObject.getJSONObject("msg")) || !"0".equals(retObject.getJSONObject("msg").getString("retCode"))
                ) {
                    yiDefineLog.setStatus("N");
                }

                yiDefineLog.setCreateId(user.getId());
                yiDefineLog.setCreateName(user.getName());
                xinYiDefineLogService.save(yiDefineLog);
            } catch (Exception e) {
                log.error("自定以新意指令创建失败:", e);
            }
        }

    }


}
